/*
package com.css.gateway.interceptor;

import com.alibaba.fastjson.JSON;
import com.css.common.core.exception.ServiceException;
import com.css.common.core.pojo.vo.GetQrcodeResVO;
import com.css.gateway.config.ApiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
@Order(-97)
public class ApiAccessFilter extends AbstractGatewayFilterFactory<Object> {

    private static final String AUTHORIZATION_HEADER = "authorization";
    private final R2dbcEntityTemplate r2dbcEntityTemplate;
    private final ApiConfig apiConfig;

    public ApiAccessFilter(R2dbcEntityTemplate r2dbcEntityTemplate, ApiConfig apiConfig) {
        super(Object.class);
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
        this.apiConfig = apiConfig;
    }

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            // 打印请求日志
            printRequest(request);

            return exchange.getSession()
                    .flatMap(webSession -> processApiAccess(exchange, chain))
                    .onErrorResume(e -> handleErrorResponse(e, response));
        };
    }

    private Mono<Void> processApiAccess(ServerWebExchange exchange, GatewayFilterChain chain) {
        return Mono.defer(() -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            // 检查接口鉴权是否启用
            if (!shouldCheckApiAccess(request)) {
                return chain.filter(exchange);
            }

            return validateAuthorizationHeader(request)
                    .flatMap(authData -> validateSignature(request, authData))
                    .flatMap(valid -> {
                        if (valid) {
                            return chain.filter(exchange);
                        } else {
                            return handleInvalidRequest(response);
                        }
                    });
        });
    }

    private boolean shouldCheckApiAccess(ServerHttpRequest request) {
        // 实现基于路由的鉴权检查逻辑
        return !apiConfig.getJqqybz() &&
                request.getPath().value().startsWith("/api/secure");
    }

    private Mono<AuthData> validateAuthorizationHeader(ServerHttpRequest request) {
        return Mono.justOrEmpty(request.getHeaders().getFirst(AUTHORIZATION_HEADER))
                .switchIfEmpty(Mono.error(new ServiceException("Authorization header missing")))
                .flatMap(this::parseAuthorizationHeader);
    }

    private Mono<AuthData> parseAuthorizationHeader(String authorization) {
        // 解析授权头逻辑（同原逻辑）
        return Mono.fromCallable(() -> {
            AuthData authData = new AuthData();
            // ... 解析逻辑
            return authData;
        });
    }

    private Mono<Boolean> validateSignature(ServerHttpRequest request, AuthData authData) {
        return getRequestBodyContent(request)
                .flatMap(body -> getAppKeyFromDB(authData.appid)
                        .flatMap(appKey -> {
                            // 实现响应式验签逻辑
                            return Mono.just(validateHmacSignature(authData, body, appKey));
                        }));
    }

    private Mono<String> getRequestBodyContent(ServerHttpRequest request) {
        return request.getBody()
                .collectList()
                .map(dataBuffers -> {
                    byte[] bytes = new byte[dataBuffers.stream().mapToInt(d -> d.readableByteCount()).sum()];
                    int offset = 0;
                    for (DataBuffer buffer : dataBuffers) {
                        int length = buffer.readableByteCount();
                        buffer.read(bytes, offset, length);
                        offset += length;
                    }
                    return new String(bytes, StandardCharsets.UTF_8);
                })
                .cache(); // 缓存请求体用于多次读取
    }

    private Mono<String> getAppKeyFromDB(String appid) {
        return r2dbcEntityTemplate.getDatabaseClient()
                .sql("SELECT appkey FROM t_ptjr WHERE gsuuid = :appid AND scbj = '0' LIMIT 1")
                .bind("appid", appid)
                .fetch()
                .one()
                .map(result -> (String) result.get("appkey"))
                .switchIfEmpty(Mono.error(new ServiceException("Invalid appid")));
    }

    private boolean validateHmacSignature(AuthData authData, String body, String appKey) {
        // 实现HMAC验签逻辑（同原逻辑）
        return true; // 示例返回值
    }

    private Mono<Void> handleErrorResponse(Throwable e, ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        GetQrcodeResVO errorRes = createErrorResponse(e.getMessage());
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(JSON.toJSONBytes(errorRes))));
    }

    private GetQrcodeResVO createErrorResponse(String errorMsg) {
        GetQrcodeResVO res = new GetQrcodeResVO();
        res.setResponseTimeStamp(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        res.setErrCode("1001");
        res.setErrMsg(errorMsg);
        return res;
    }

    private void printRequest(ServerHttpRequest request) {
        log.info("Request Path: {}, Method: {}, Headers: {}",
                request.getPath(),
                request.getMethod(),
                request.getHeaders());
    }

    // 辅助数据结构
    private static class AuthData {
        String appid;
        String timestamp;
        String nonce;
        String signature;
    }
}

*/
